package com.haochang.chunkvod.app.utils;

import java.util.ArrayList;
import java.util.List;

import com.haochang.base.VodApplication;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.model.hostess.IpInfo;

import android.content.res.XmlResourceParser;

/**XmlResourceParser 解析工具
 *     @author Yangjie
 *     className XmlResourceParserUtil
 *     created at  2016/11/11  19:45
 */
public class XmlResourceParserUtil
{
	private static XmlResourceParserUtil instance;

	public static XmlResourceParserUtil getInstance()
	{
		if (instance == null)
		{
			synchronized (XmlResourceParserUtil.class)
			{
				if (instance == null)
					instance = new XmlResourceParserUtil();
			}
		}
		return instance;
	}

	/**
	 * 释放静态对象
	 */
	public void releaseInstance()
	{
		if (instance != null)
			instance = null;
	}

	public List<IpInfo> parseXML()
	{
		List<IpInfo> list = new ArrayList<IpInfo>();
		if (VodApplication.appContext == null)
			return null;
		IpInfo ipInfo = null;
		IpInfo ipInfoChild = null;
		XmlResourceParser xmlResourceParser = VodApplication.appContext.getResources().getXml(R.xml.ipconfig);
		try
		{
			while (xmlResourceParser.getEventType() != XmlResourceParser.END_DOCUMENT)
			{
				if (xmlResourceParser.getEventType() == XmlResourceParser.START_TAG)
				{
					String tagName = xmlResourceParser.getName();
					if (tagName.equals("city"))
					{
						String cityName = xmlResourceParser.getAttributeValue(0);
						ipInfo = new IpInfo();
						ipInfo.setCity(cityName);
					} else if (tagName.equals("shop"))
					{
						String shop = xmlResourceParser.getAttributeValue(0);
						ipInfoChild = new IpInfo();
						ipInfoChild.setShop(shop);
					} else if (tagName.equals("ip"))
					{
						String ip = xmlResourceParser.getAttributeValue(0);
						if (null != ipInfoChild && null != ipInfo)
						{
							ipInfoChild.setIp(ip);
							ipInfoChild.setCity(ipInfo.getCity());
							ipInfo.getArrayList().add(ipInfoChild);
						}
					}

				} else if (xmlResourceParser.getEventType() == XmlResourceParser.END_TAG)
				{
					String tagName = xmlResourceParser.getName();
					if (tagName.equals("city"))
					{
						if (ipInfo != null)
						{
							list.add(ipInfo);
						}
					}

				}
				xmlResourceParser.next();
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}

}
